<template>
	<view class="region-container">
		<view class="image-wrapper" :style="{ width: displayWidth + 'px', height: displayHeight + 'px' }">
			<image class="scaled-image" :src="imgConfig.url"
				:style="{ width: displayWidth + 'px', height: displayHeight + 'px' }" mode="widthFix"
				@load="onImageLoad"></image>

			<view class="polygons-container">
				<view v-for="(line, index) in processedLines" :key="index" class="polygon-wrapper" :style="{
						width: displayWidth + 'px',
						height: displayHeight + 'px'
					}">
					<view class="polygon-fill" :style="{
							clipPath: `polygon(${line.pointsString})`,
							backgroundColor: line.fillStyle
						}"></view>

					<view v-for="(edge, edgeIndex) in line.edges" :key="edgeIndex" class="polygon-edge" :style="{
							left: edge.startX + 'px',
							top: edge.startY + 'px',
							width: edge.length + 'px',
							height: edge.width + 'px',
							backgroundColor: line.strokeColor,
							transformOrigin: '0 50%',
							transform: `rotate(${edge.angle}rad)`
						}"></view>
				</view>
			</view>

			<view v-if="processedMarkers.length" class="markers-container"
				:style="{ width: displayWidth + 'px', height: displayHeight + 'px' }">
				<view style="position: relative;">
					<view v-for="(marker, index) in processedMarkers" :key="marker.id || index" class="marker-item"
						:style="{
										left: marker.scaledX + 'px',
										top: marker.scaledY + 'px',
										transform: `translate(-50%, -50%)`
									  }" @click="handleMarkerClick(marker)">
						<view class="marker-icon-wrapper" :class="marker.className">
							<image :src="marker.iconUrl || defaultMarkerIcon" :style="{ 
					  width: marker.size + 'px', 
					  height: marker.size + 'px'
					}" class="marker-icon" :class="{'marker-active': selectedMarkerId === marker.id}" />
						</view>
						<view v-if="marker.labels && selectedMarkerId === marker.id" class="marker-labels-wrapper">
							<view class="marker-labels">
								<view v-for="(label, idx) in marker.labels" :key="idx" class="label-text">
									{{ label }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			imgConfig: {
				type: Object,
				required: true,
				default: () => ({})
			},
			markers: {
				type: Array,
				default: () => []
			},
			lines: {
				type: Array,
				default: () => []
			},
		},
		watch: {
			imgConfig: {
				deep: true,
				handler() {
					this.calculateImageSize();
				}
			},
		},
		data() {
			return {
				displayWidth: 0, // 显示宽度
				displayHeight: 0, // 显示高度
				scaleRatio: 1, // 缩放比例
				defaultMarkerIcon: 'https://picsum.photos/30/30', // 默认标记图标
				selectedMarkerId: null, // 当前选中的标记点ID
			};
		},

		computed: {
			processedMarkers() {
				if (!this.markers || !this.markers.length || !this.scaleRatio) return [];

				return this.markers.map(marker => {
					const x = marker.coorX !== undefined ? marker.coorX : marker.x;
					const y = marker.coorY !== undefined ? marker.coorY : marker.y;
					const size = marker.iconSize !== undefined ? marker.iconSize :
						(marker.width || marker.height || 30);

					return {
						...marker,
						x,
						y,
						scaledX: x * this.scaleRatio,
						scaledY: y * this.scaleRatio,
						size: size
					};
				});
			},

			processedLines() {
				if (!this.lines || !this.lines.length || !this.scaleRatio) return [];

				return this.lines.map(line => {
					if (line.type !== 'Polygon' || !Array.isArray(line.lineList) || line.lineList.length < 3) {
						return null;
					}

					const points = line.lineList.map(point => ({
						x: (point.coorX !== undefined ? point.coorX : point.x) * this.scaleRatio,
						y: (point.coorY !== undefined ? point.coorY : point.y) * this.scaleRatio
					}));
					const pointsString = points.map(p => `${p.x}px ${p.y}px`).join(', ');
					let fillStyle = 'transparent';
					if (line.style.fill && line.style.fillColor) {
						const hex = line.style.fillColor.replace('#', '');
						const r = parseInt(hex.substring(0, 2), 16);
						const g = parseInt(hex.substring(2, 4), 16);
						const b = parseInt(hex.substring(4, 6), 16);
						const opacity = line.style.fillOpacity || 1;
						fillStyle = `rgba(${r}, ${g}, ${b}, ${opacity})`;
					}

					const strokeColor = line.style.color || '#000';
					const strokeWidth = line.style.width || 1;

					const edges = [];
					for (let i = 0; i < points.length - 1; i++) {
						edges.push(this.calculateEdge(points[i], points[i + 1], strokeWidth));
					}

					if (points.length > 1) {
						edges.push(this.calculateEdge(points[points.length - 1], points[0], strokeWidth));
					}

					return {
						...line,
						pointsString,
						fillStyle,
						strokeColor,
						strokeWidth,
						edges
					};
				}).filter(Boolean); 
			}
		},

		mounted() {
			this.calculateImageSize();
		},

		methods: {
			calculateEdge(point1, point2, width) {
				const dx = point2.x - point1.x;
				const dy = point2.y - point1.y;
				const length = Math.sqrt(dx * dx + dy * dy);

				const angle = Math.atan2(dy, dx);

				return {
					startX: point1.x,
					startY: point1.y,
					length,
					width,
					angle
				};
			},
			onImageLoad(){
				this.$emit('loadFnish')
			},
			calculateImageSize() {
				const {
					width,
					height
				} = this.imgConfig;
				if (!width || !height) return;

				const {
					windowWidth
				} = uni.getSystemInfoSync();
				const screenWidth = windowWidth;
				const expectedHeight = (height / width) * screenWidth;
				const maxHeight = uni.upx2px(500);

				this.displayWidth = screenWidth;
				this.displayHeight = Math.min(expectedHeight, maxHeight);
				this.scaleRatio = this.displayWidth / width;

				this.$emit('resize', {
					width: this.displayWidth,
					height: this.displayHeight,
					scaleRatio: this.scaleRatio
				});
			},
			handleMarkerClick(marker) {
				this.selectedMarkerId = this.selectedMarkerId === marker.id ? null : marker.id;
				this.$emit('markerClick', marker);
			}
		}
	}
</script>

<style scoped>
	.region-container {
		position: relative;
		overflow: hidden;
		border-radius: 8px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	}

	.image-wrapper {
		position: relative;
		margin: 0 auto;
		background-color: #f8f8f8;
	}

	.scaled-image {
		display: block;
		object-fit: contain;
	}

	.polygons-container {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 5;
		pointer-events: none;
	}

	.polygon-wrapper {
		position: absolute;
		top: 0;
		left: 0;
	}

	.polygon-fill,
	.polygon-stroke {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none;
	}

	.polygon-stroke {
		box-sizing: border-box;
		border-style: solid;
		background-color: transparent;
	}

	.markers-container {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
	}

	.marker-item {
		position: absolute;
		pointer-events: auto;
		cursor: pointer;
	}

	.marker-icon-wrapper {
		width: 100%;
		height: 100%;
		transition: transform 0.2s ease;
	}

	.marker-icon {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.marker-labels-wrapper {
		position: absolute;
		bottom: calc(100% + 8px);
		left: 50%;
		transform: translateX(-50%);
		pointer-events: none;
		white-space: nowrap;
		z-index: 50;
	}

	.marker-labels {
		background-color: rgba(0, 0, 0, 0.8);
		color: white;
		padding: 6px 10px;
		border-radius: 4px;
		font-size: 12px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
	}

	.label-text {
		line-height: 1.5;
	}

	.marker-active {
		transform: scale(1.1);
	}

	.polygon-edge {
		position: absolute;
		transform-origin: 0 50%;
		pointer-events: none;
		border-radius: 2px;
	}
</style>